package order.service;


import jakarta.annotation.PostConstruct;
import lombok.extern.slf4j.Slf4j;
import order.mapper.OrderMapper;
import order.model.OrderInfo;
import order.model.ProductInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * Created with Intellij IDEA.
 * Description;
 * User:TQ02
 * Data:2024-07-18
 * Time:12:42
 * Text：
 */
@Slf4j
@Service
public class OrderService {
    @Autowired
    private OrderMapper orderMapper;
    //发送url请求数据
    @Autowired
    private RestTemplate restTemplate;
    //从服务注册中心（如 Eureka、Consul 等）获取服务实例信息
    @Autowired
    private DiscoveryClient discoveryClient;
    //计数器
    private AtomicInteger count = new AtomicInteger(1);

    private List<ServiceInstance> instances;
    @PostConstruct
    public void init(){
        //从Eureka中获取服务列表
        instances = discoveryClient.getInstances("product-service");
    }


    public OrderInfo selectOrderById(Integer id){
        OrderInfo orderInfo =  orderMapper.select(id);
//        String url = "http://127.0.0.1:8081/product/"+orderInfo.getProductId();
        //获取Eureka中的服务列表
//        方法一，手工均衡计算轮流的实例idnex
//        int index= count.getAndIncrement() % instances.size();
//        String url = instances.get(index).getUri().toString()+"/product/"+orderInfo.getProductId();
        //方法二：自动，默认轮询
        String url = "http://product-service/product/"+orderInfo.getProductId();
        log.info("远程调用url:{}", url);
        ProductInfo productInfo = restTemplate.getForObject(url, ProductInfo.class);
        orderInfo.setPorductInfo(productInfo);
        return orderInfo;
    }
}
